import axios from 'axios';

import {
    Message
} from 'element-ui'
import store from '../vuex/store'

const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    // baseURL: 'https://www.easy-mock.com/mock/592501a391470c0ac1fab128',
    timeout: 15000
});

//请求拦截
service.interceptors.request.use(
    config => {
        //放入token和账套id
        let token = store.state.token_mark;
        console.log('token request', token)
        config.headers.token_mark = token;
        config.headers.set_book_id = store.state.accountSet.id;
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            //如果有token的话就放到本地
            if (response.headers.token_mark) {
                store.commit('changeToken', response.headers.token_mark);
                console.log('response.headers.token_mark', response.headers.token_mark)
                // sessionStorage.setItem('token_mark', response.headers.token_mark)
            }
            return response.data;
        } else {
            Message({
                showClose: true,
                message: '服务器繁忙，请稍后再试',
                type: 'error'
            });
            Promise.reject();
        }
    },
    error => {
        if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    error.message = '请求错误(400)';
                    break;
                case 401:
                    window.sessionStorage.clear();
                    break;
                case 403:
                    window.sessionStorage.clear();
                    break;
                case 404:
                    error.message = '请求出错(404)';
                    break;
                case 408:
                    error.message = '请求超时(408)';
                    break;
                case 500:
                    error.message = '服务器错误(500)';
                    break;
                case 501:
                    error.message = '服务未实现(501)';
                    break;
                case 502:
                    error.message = '网络错误(502)';
                    break;
                case 503:
                    error.message = '服务不可用(503)';
                    break;
                case 504:
                    error.message = '网络超时(504)';
                    break;
                case 505:
                    error.message = 'HTTP版本不受支持(505)';
                    break;
            }
        } else {
            error.message = '连接服务器失败!'
        }
        Message({
            showClose: true,
            message: '服务器繁忙，请稍后再试',
            type: 'error'
        });
        return Promise.reject();
    }
);

export default service;